package com.ithuameng.cosy.component.handler;

import com.ithuameng.cosy.component.handler.annotation.CIMHandler;
import com.ithuameng.cosy.model.Session;
import com.ithuameng.cosy.constant.ChannelAttr;
import com.ithuameng.cosy.group.SessionGroup;
import com.ithuameng.cosy.handler.CIMRequestHandler;
import com.ithuameng.cosy.model.SentBody;
import com.ithuameng.cosy.service.ISessionService;
import io.netty.channel.Channel;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 连接断开时，更新用户相关状态
 */
@CIMHandler(key = "client_closed")
public class ClosedHandler implements CIMRequestHandler {

    @Resource
    private ISessionService sessionService;

    @Resource
    private SessionGroup sessionGroup;

    @Override
    public void process(Channel channel, SentBody message) {

        String uid = channel.attr(ChannelAttr.UID).get();

        if (uid == null) {
            return;
        }

        String nid = channel.attr(ChannelAttr.ID).get();

        sessionGroup.remove(channel);

		/*
         * ios开启了apns也需要显示在线，因此不删记录
		 */
        if (!Objects.equals(channel.attr(ChannelAttr.CHANNEL).get(), Session.CHANNEL_IOS)) {
            sessionService.delete(uid, nid);
            return;
        }

        sessionService.updateState(uid, nid, Session.STATE_INACTIVE);
    }
}
